package com.pth.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.pth.dao.JianjieDAO;
import com.pth.model.Jianjie;
import com.pth.utils.JianjieSign;

public class JianjieDAOImpl implements JianjieDAO {

	private HibernateTemplate hibernateTemplate;
	
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void add(Jianjie jianjie) {

		hibernateTemplate.save(jianjie);
		
	}

	public void delete(Jianjie jianjie) {

		hibernateTemplate.delete(jianjie);
		
	}

	public Jianjie getJianjieByid(int id) {

		return hibernateTemplate.get(Jianjie.class, id);
	
	}

	public int getJianjieNum() {

		String hql="from Jianjie j where j.sign="+JianjieSign.CONTENT;
		return hibernateTemplate.find(hql).size();
	
	}


	@SuppressWarnings("unchecked")
	public List<Jianjie> getJianjies(final int pagesize,final int offset,int sign) {

		final String hqlString="from Jianjie j where j.sign="+sign+" order by j.publishtime desc";
		
		List<Jianjie> list=hibernateTemplate.executeFind(new HibernateCallback() {

			public Object doInHibernate(Session arg0) throws HibernateException,
					SQLException {

				return arg0.createQuery(hqlString).setFirstResult(offset).setMaxResults(pagesize).list();
				
			}
		});
		
		return list;
		
	}

	public void update(Jianjie jianjie) {


		hibernateTemplate.update(jianjie);

	}

	@SuppressWarnings("unchecked")
	public List<Jianjie> getJianjiesOrderByScanNum(final int pagesize,final int offset,int sign) {

		final String hqlString="from Jianjie j where j.sign="+sign+" order by j.scannum desc";
		
		List<Jianjie> list=hibernateTemplate.executeFind(new HibernateCallback() {

			public Object doInHibernate(Session arg0) throws HibernateException,
					SQLException {

				return arg0.createQuery(hqlString).setFirstResult(offset).setMaxResults(pagesize).list();
				
			}
		});
		
		return list;
		
	}

	@SuppressWarnings("unchecked")
	public List<Jianjie> getAllJianjies() {

		return hibernateTemplate.find("from Jianjie ");
		
	}

}
